import api from '../../../api/api.js'
import utils from '../../templates/loader/loader.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataArray: {},
    display: false,
    orderStatus: [{
        "id": 0,
        "active": true,
        "text": ""
      },
      {
        "id": 1,
        "active": true
      },
      {
        "id": 2,
        "active": true
      },
      {
        "id": 3,
        "active": true
      },
      {
        "id": 4,
        "active": true
      }
    ],
    btnLock: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var json = JSON.parse(options.jsonData);
    that.data.orderStatus.forEach(function (item) {
      if (json.orderStatus == null) {
        if (json.paymentStatus < item.id)
          item.active = false
      } else {
        if (json.orderStatus < item.id)
          item.active = false
      }
    })
    var paymentTime = json.paymentTime;
    var time1 = paymentTime.split(/[^0-9]/);
    json.paymentTime = that.dateFtt("yyyy-MM-dd hh:mm:ss", new Date(time1[0], time1[1] - 1, time1[2], time1[3], time1[4], time1[5]));
    var createTime = json.createTime;
    var time2 = createTime.split(/[^0-9]/);
    json.createTime = that.dateFtt("yyyy-MM-dd hh:mm:ss", new Date(time2[0], time2[1] - 1, time2[2], time2[3], time2[4], time2[5]));``
    if (json.orderStatus == null) {
      switch (json.paymentStatus) {
        case "0":
          json.orderStatusText = "已下单等待付款";
          break;
        case "1":
          json.orderStatusText = "已付款等待发货";
          break;
      }
    } else {
      switch (json.orderStatus) {
        case "0":
          json.orderStatusText = "已下单等待付款";
          break;
        case "1":
          json.orderStatusText = "已付款等待发货";
          break;
        case "2":
          json.orderStatusText = "已发货等待收货";
          break;
        case "3":
          json.orderStatusText = "";
          break;
        case "4":
          json.orderStatusText = "已取消";
          break;
      }
    }
    that.setData({
      dataArray: json,
      display: true,
      orderStatus: that.data.orderStatus
    });
  },
  cancelOrder: function (e) {
    var that = this
    var selfData = e.currentTarget.dataset
    wx.showModal({
      title: '提示',
      content: '确定取消订单？',
      confirmColor: "#e30c26",
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中...',
            mask:true
          })
          var jsonStr = '{ "REQ_HEAD":{ "SIGN":"null" },"REQ_BODY": { "id": "' + selfData.orderid + '", "userId": "' + that.data.userInfo.id + '" }}'
          api.cancelOrder({
            method: 'POST',
            data: {
              REQ_MESSAGE: jsonStr
            },
            complete: (res) => {
              wx.hideLoading()
              that.loader.close()
              if (res.statusCode == "200") {
                if (res.data.REP_BODY.RSPCOD == "000000") {
                  wx.showToast({
                    title: '取消订单成功',
                    icon: 'success',
                    duration: 2000
                  })
                  that.setData({
                    btnLock: true
                  })
                } else {
                  wx.showToast({
                    title: '取消订单成功',
                    image: '/image/ico/error-ico.png',
                    duration: 2000
                  })
                }
              } else {
                wx.showToast({
                  title: '取消订单成功',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            }
          })
        }
      }
    })
  },
  getRefund: function (e) {
    var that = this;
    var json = '{"REQ_HEAD":{ "SIGN":"null" },"REQ_BODY": { "orderId": "' + e.currentTarget.dataset.orderid + '", "userId": "' + that.data.userInfo.id + '" }}'
    wx.showModal({
      title: '提示',
      content: '确定退款？',
      confirmColor: "#e30c26",
      complete: function (res) {
        if (res.confirm) {
          wx.showLoading({
            mask:true
          })
          api.getRefund({
            method: 'POST',
            data: {
              REQ_MESSAGE: json
            },
            success: (res) => {
              wx.hideLoading()
              if (res.statusCode == 200) {
                if (res.data.REP_BODY.RSPCOD == "000000") {
                  wx.showToast({
                    title: '提交成功',
                    icon: 'success',
                    duration: 3000
                  })
                  that.data.orderlist.forEach(function (item) {
                    if (e.currentTarget.dataset.orderid == item.id) {
                      item.refundStatus = 2;
                    }
                  });
                  that.setData({
                    orderlist: that.data.orderlist
                  })
                } else {
                  if (res.data.REP_BODY.RSPCOD) {
                    wx.showModal({
                      title: '提示',
                      content: res.data.REP_BODY.RSPCOD,
                      confirmColor: "#e30c26"
                    })
                  } else {
                    wx.showToast({
                      title: '退款失败',
                      image: '/image/ico/error-ico.png',
                      duration: 2000
                    })
                  }
                }
              } else {
                wx.showToast({
                  title: '退款失败',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            }
          })
        }
      }
    })
  },
  pay: function (e) {
    wx.showLoading({
      mask:true
    })
    var that = this
    wx.login({
      success: function (data) {
        api.payOrder({
          method: 'POST',
          data: {
            orderId: e.currentTarget.dataset.orderno,
            code: data.code,
            userId:that.data.userInfo.id
          },
          complete: (res) => {
            wx.hideLoading()
            if (res.statusCode == 200) {
              if (res.data) {
                wx.requestPayment({
                  'timeStamp': res.data.timeStamp,
                  'nonceStr': res.data.nonceStr,
                  'package': res.data.packageValue,
                  'signType': 'MD5',
                  'paySign': res.data.sign,
                  'success': function (res) {
                    if (res.errMsg == "requestPayment:ok") {
                      wx.redirectTo({
                        url: '/pages/order/orderlist/orderlist?type=1',
                      })
                    } else {
                      wx.showToast({
                        title: '支付失败!',
                        image: '/image/ico/error-ico.png',
                        duration: 2000
                      })
                    }
                  },
                  'fail': function (res) {
                    if (res.errMsg == "requestPayment:fail cancel") {
                      // wx.redirectTo({
                      //   url: '/pages/order/orderlist/orderlist?type=0',
                      // })
                    } else {
                      wx.showToast({
                        title: '支付失败!',
                        image: '/image/ico/error-ico.png',
                        duration: 2000
                      })
                    }
                  }
                })
              } else {
                wx.showToast({
                  title: '缺少参数!',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            }
          },
          fail: (res) => {
            wx.showToast({
              title: '支付失败!',
              image: '/image/ico/error-ico.png',
              duration: 2000
            })
          }
        })
      }
    })
  },
  confirmOrder: function (e) {
    wx.showModal({
      title: '提示',
      content: '确定收货？',
      confirmColor: "#e30c26",
      success: function (res) {
        var json = '{"REQ_HEAD":{ "SIGN":"null" },"REQ_BODY": { "id": "' + e.currentTarget.dataset.orderid + '","infoId":"' + e.currentTarget.dataset.infoid + '"}}';
        if (res.confirm) {
          wx.showLoading({
            mask:true
          })
          api.confirmOrder({
            method: 'POST',
            data: {
              REQ_MESSAGE: json
            },
            complete: (res) => {
              wx.hideLoading();
              if (res.statusCode == 200) {
                if (res.data.REP_BODY.RSPCOD == "000000") {
                  wx.showToast({
                    title: '收货成功!',
                    icon: 'success',
                    mask: true,
                    duration: 2000
                  });
                  setTimeout(function () {
                    wx.switchTab({
                      url: '../../myPan/index/index',
                    });
                  }, 2000);
                } else {
                  wx.showToast({
                    title: '收货失败!',
                    image: '/image/ico/error-ico.png',
                    duration: 2000
                  });
                }
              } else {
                wx.showToast({
                  title: '收货失败!',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                });
              }
            }
          })
        }
      }
    })
  },dateFtt: function (fmt, date) {
    var o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }
})